package com.ruoyi.campus.websocket;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 报警WebSocket服务器
 * 
 * @author campus-alarm
 * @date 2024-01-01
 */
@Component
@ServerEndpoint("/campus-websocket/{clientId}")
public class AlarmWebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(AlarmWebSocketServer.class);

    /** 静态变量，用来记录当前在线连接数 */
    private static int onlineCount = 0;

    /** concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象 */
    private static CopyOnWriteArraySet<AlarmWebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /** 与某个客户端的连接会话，需要通过它来给客户端发送数据 */
    private Session session;

    /** 接收clientId */
    private String clientId = "";

    /** 用于存储在线用户信息 */
    private static ConcurrentHashMap<String, AlarmWebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        this.session = session;
        this.clientId = clientId;
        webSocketSet.add(this);
        webSocketMap.put(clientId, this);
        addOnlineCount();
        log.info("用户连接:" + clientId + ",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:" + clientId + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        webSocketMap.remove(this.clientId);
        subOnlineCount();
        log.info("用户退出:" + clientId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + clientId + ",报文:" + message);
        // 处理心跳消息
        if ("ping".equals(message)) {
            try {
                sendMessage("pong");
            } catch (IOException e) {
                log.error("心跳回复失败", e);
            }
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.clientId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("clientId") String clientId) throws IOException {
        log.info("发送消息到:" + clientId + ",报文:" + message);
        if (clientId != null && webSocketMap.containsKey(clientId)) {
            webSocketMap.get(clientId).sendMessage(message);
        } else {
            log.error("用户" + clientId + ",不在线！");
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfoToAll(String message) throws IOException {
        log.info("推送消息到全部，报文:" + message);
        for (AlarmWebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                log.error("推送失败", e);
                continue;
            }
        }
    }

    /**
     * 发送报警消息
     */
    public static void sendAlarmMessage(String clientId, Object alarmData) {
        try {
            String message = JSON.toJSONString(alarmData);
            sendInfo(message, clientId);
        } catch (IOException e) {
            log.error("发送报警消息失败", e);
        }
    }

    /**
     * 广播报警消息
     */
    public static void broadcastAlarmMessage(Object alarmData) {
        try {
            String message = JSON.toJSONString(alarmData);
            sendInfoToAll(message);
        } catch (IOException e) {
            log.error("广播报警消息失败", e);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        AlarmWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        AlarmWebSocketServer.onlineCount--;
    }
} 